#include "cpu/exec/template-start.h"
#include "cpu/decode/modrm.h"

make_helper(add_si2rm_v) {
        //获取指令的长度
    int len = decode_si2rm_l(eip + 1);
    Log("len = %d", len);
    ModR_M m;
    m.val = instr_fetch(eip + 1, 1); // 从 eip + 1 处获取一个字节，作为 ModR/M 字节


    if (m.mod == 3) { // 如果 mod 字段为 3，表示寄存器+立即数
        switch (op_dest->reg) {
            case 0: cpu.eax += op_src->val; break;
            case 1: cpu.ecx += op_src->val; break;
            case 2: cpu.edx += op_src->val; break;
            case 3: cpu.ebx += op_src->val; break;
            case 4: cpu.esp += op_src->val; break;
            case 5: cpu.ebp += op_src->val; break;
            case 6: cpu.esi += op_src->val; break;
            case 7: cpu.edi += op_src->val; break;
            default: Assert(0, "add_si2rm_v error");
        }
        // 更新 eip
        print_asm("add" str(SUFFIX) " $0x%x,%%%s", op_src->val, REG_NAME(op_dest->reg));
        
        // int len = read_ModR_M(eip + 1, &m, op_src);
        // Log("len = %d", len);
        return len + 1;
    } else {
        // 如果 mod 字段不为 3，表示内存+立即数
        // Log("op_src->val = %x", op_src->val);
        // Log("op_dest->addr = %x", op_dest->addr);
        //进行内存操作
        DATA_TYPE srcmem = hwaddr_read(op_dest->addr, DATA_BYTE);
        DATA_TYPE result = srcmem + op_src->val;
        hwaddr_write(op_dest->addr, DATA_BYTE, result);
        // 更新 eip
        print_asm("add" str(SUFFIX) " $0x%x,%s", op_src->val, op_dest->str);
        

        return len + 1;
    }
}

#include "cpu/exec/template-end.h"